package com.weipeep.common.utils.httpclient.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOUtil {
	public static final String BOUNDARY = "---------------------------123821742118716";
	private static final String NEW_LINE = "\r\n";

	public static void copy(InputStream _in, OutputStream _out) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(_in);
			out = new BufferedOutputStream(_out);
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = in.read(b, 0, b.length)) != -1) {
				out.write(b, 0, len);
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(in, out);
		}
	}

	public static void close(InputStream in, OutputStream out) {
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (out != null) {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 *  conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);  
	 * @param key
	 * @param file
	 */
	public static byte[] toFormData(final String key, final File file) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			copy(new FileInputStream(file), out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return writeToOutputStream(key, file.getName(),out.toByteArray());
	}

	public static byte[] writeToOutputStream(String paramName,String fileName, byte[] rawData) {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			out.write(writeBoundary(true));
			out.write(getContentDispositionBytes(paramName, fileName));
			out.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes());
			// 数据这边两个\r\n
			out.write(rawData);
			out.write((NEW_LINE).getBytes());
			out.flush();
			return out.toByteArray();
		} catch (final IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static byte[] getContentDispositionBytes(String paramName, String fileName) {
		String str = "Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n";
		return str.getBytes();
	}

	public static byte[] writeBoundary(boolean first) throws IOException {
		if (first) {
			return ("--" + BOUNDARY + NEW_LINE).getBytes();
		}
		return ("--" + BOUNDARY + "--" + NEW_LINE).getBytes();
	}

}
